package com.example.flower_shop.repository;

import com.example.flower_shop.entity.CustomerOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface CustomerOrderRepository extends JpaRepository<CustomerOrder, Long> {
    Optional<CustomerOrder> findByOrderNo(String orderNo);

    @Query("SELECT o FROM CustomerOrder o WHERE o.status = :status AND (o.deleted = false OR o.deleted IS NULL)")
    Page<CustomerOrder> findByStatus(@Param("status") Integer status, Pageable pageable);

    @Query("SELECT co FROM CustomerOrder co JOIN MerchantOrder mo ON co.id = mo.customerOrderId WHERE mo.merchantId = :merchantId AND (co.deleted = false OR co.deleted IS NULL)")
    Page<CustomerOrder> findByMerchantId(@Param("merchantId") Long merchantId, Pageable pageable);

    @Query("SELECT co FROM CustomerOrder co JOIN MerchantOrder mo ON co.id = mo.customerOrderId WHERE mo.merchantId = :merchantId AND co.status = :status AND (co.deleted = false OR co.deleted IS NULL)")
    Page<CustomerOrder> findByMerchantIdAndStatus(
            @Param("merchantId") Long merchantId,
            @Param("status") Integer status,
            Pageable pageable);

    @Query("SELECT o FROM CustomerOrder o WHERE o.user.id = :userId AND (o.deleted = false OR o.deleted IS NULL) ORDER BY o.createTime DESC")
    Page<CustomerOrder> findByUserIdOrderByCreateTimeDesc(@Param("userId") Long userId, Pageable pageable);

    @Query("SELECT o FROM CustomerOrder o WHERE o.user.id = :userId AND (o.deleted = false OR o.deleted IS NULL)")
    Page<CustomerOrder> findByUserIdAndNotDeleted(@Param("userId") Long userId, Pageable pageable);

    @Query("SELECT o FROM CustomerOrder o WHERE o.user.id = :userId AND o.status = :status AND (o.deleted = false OR o.deleted IS NULL)")
    Page<CustomerOrder> findByUserIdAndStatusAndNotDeleted(@Param("userId") Long userId,
            @Param("status") Integer status, Pageable pageable);

    @Query("SELECT o FROM CustomerOrder o WHERE o.orderNo = :orderNo AND (o.deleted = false OR o.deleted IS NULL)")
    Optional<CustomerOrder> findByOrderNoAndNotDeleted(@Param("orderNo") String orderNo);
}